import numpy as np
import cv2
# FLANN特征匹配

img1 = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\op1.jpg")
img2 = cv2.imread("C:\\Users\\86191\\Pictures\\Saved Pictures\\Camera Roll\\op2.jpg")
# 灰度化
g1 = cv2.cvtColor(img1, cv2.COLOR_BGR2GRAY)
g2 = cv2.cvtColor(img2, cv2.COLOR_BGR2GRAY)
# 创建sift对象
sift = cv2.SIFT_create()
# 计算描述子
kp1,des1= sift.detectAndCompute(g1,None)
kp2,des2= sift.detectAndCompute(g2,None)
# 创建特征匹配器
index_params = dict(algorithm=1, trees=5)
search_params = dict(checks = 50)
flann = cv2.FlannBasedMatcher(index_params,search_params)
# 匹配
match = flann.knnMatch(des1,des2,k=2)
# 筛选特征点
good = []
for i,(m,n) in enumerate(match):
    if m.distance < 0.7*n.distance:
        good.append(m)

ret = cv2.drawMatchesKnn(img1,kp1,img2,kp2,[good],None)
cv2.imshow("result",ret)
cv2.waitKey(0)